import React, { useState, useRef, useEffect } from 'react';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import {
  AppBar,
  Badge,
  Box,
  Collapse,
  Divider,
  Drawer,
  IconButton,
  List,
  ListItem,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Toolbar,
  Tooltip,
  Typography,
} from '@mui/material';
import {
  Close as CloseIcon,
  Menu as MenuIcon,
  Notifications as NotificationsIcon,
  Settings as SettingsIcon,
  Storage as StorageIcon,
  Terminal as TerminalIcon,
  VpnKey as VpnKeyIcon,
  Computer as ComputerIcon,
  Tune as TunnelIcon,
  Info as InfoIcon,
  ExpandLess as ExpandLessIcon,
  ExpandMore as ExpandMoreIcon,
  PlayArrow as PlayArrowIcon,
} from '@mui/icons-material';
import { Terminal as XTerm } from 'xterm';
import { FitAddon } from 'xterm-addon-fit';
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import toast from 'react-hot-toast';

// Store
import { useAppStore } from '../store/appStore';


const DRAWER_WIDTH = 280;

interface NavigationItem {
  path: string;
  label: string;
  icon: React.ReactNode;
  description?: string;
}

const navigationItems: NavigationItem[] = [
  {
    path: '/connections',
    label: '连接管理',
    icon: <ComputerIcon />,
    description: '管理SSH连接配置',
  },
  {
    path: '/terminal',
    label: '终端',
    icon: <TerminalIcon />,
    description: 'SSH终端会话',
  },
  {
    path: '/tunnels',
    label: '隧道管理',
    icon: <TunnelIcon />,
    description: '端口转发和隧道',
  },
  {
    path: '/settings',
    label: '设置',
    icon: <SettingsIcon />,
    description: '应用程序设置',
  },
];

const Layout: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const {
    sidebarOpen,
    setSidebarOpen,
    notifications,
    activeConnections,
    terminals,
    tunnels,
  } = useAppStore();

  // 本地终端状态
  const [localTerminalOpen, setLocalTerminalOpen] = useState(false);
  const [localTerminalHeight, setLocalTerminalHeight] = useState(300);
  const terminalRef = useRef<HTMLDivElement>(null);
  const xtermRef = useRef<XTerm | null>(null);
  const fitAddonRef = useRef<FitAddon | null>(null);
  const [localTerminalId, setLocalTerminalId] = useState<string | null>(null);

  // 计算未读通知数量
  const unreadNotifications = notifications.filter(n => !n.read).length;

  // 计算活动状态
  const activeConnectionsCount = activeConnections.filter(c => c.status.status === 'connected').length;
  const activeTerminalsCount = terminals.filter(t => t.status.status === 'active').length;
  const activeTunnelsCount = tunnels.filter(t => t.status.status === 'running').length;

  const handleNavigate = (path: string) => {
    navigate(path);
  };

  const toggleSidebar = () => {
    setSidebarOpen(!sidebarOpen);
  };

  // 初始化本地终端
  const initializeLocalTerminal = useCallback(async () => {
    if (localTerminalId || !terminalRef.current) return;

    try {
      // 调用后端API创建本地shell进程
      const terminalId = await invoke('create_local_terminal') as string;
      setLocalTerminalId(terminalId);

      // 初始化xterm.js实例
      const terminal = new XTerm({
        fontFamily: 'SF Mono, Monaco, Consolas, monospace',
        fontSize: 14,
        cursorStyle: 'block',
        cursorBlink: true,
        scrollback: 10000,
        theme: {
          background: '#1a1a1a',
          foreground: '#ffffff',
          cursor: '#ffffff',
          black: '#000000',
          red: '#e06c75',
          green: '#98c379',
          yellow: '#d19a66',
          blue: '#61afef',
          magenta: '#c678dd',
          cyan: '#56b6c2',
          white: '#ffffff',
          brightBlack: '#5c6370',
          brightRed: '#e06c75',
          brightGreen: '#98c379',
          brightYellow: '#d19a66',
          brightBlue: '#61afef',
          brightMagenta: '#c678dd',
          brightCyan: '#56b6c2',
          brightWhite: '#ffffff',
        },
      });

      const fitAddon = new FitAddon();
      terminal.loadAddon(fitAddon);
      
      terminal.open(terminalRef.current);
      fitAddon.fit();
      
      xtermRef.current = terminal;
      fitAddonRef.current = fitAddon;

      // 处理用户输入
      terminal.onData(async (data) => {
        try {
          await invoke('local_terminal_input', {
            terminalId,
            data,
          });
        } catch (error) {
          console.error('Failed to send local terminal input:', error);
          toast.error('发送终端输入失败');
        }
      });
      
      toast.success('本地终端已启动');
    } catch (error) {
      console.error('Failed to initialize local terminal:', error);
      toast.error('启动本地终端失败');
    }
  }, [localTerminalId]);

  // 切换本地终端显示
  const toggleLocalTerminal = () => {
    const newOpen = !localTerminalOpen;
    setLocalTerminalOpen(newOpen);
    
    if (newOpen && !xtermRef.current) {
      // 延迟初始化，确保DOM已渲染
      setTimeout(initializeLocalTerminal, 100);
    }
  };

  // 关闭本地终端
  const closeLocalTerminal = useCallback(async () => {
    if (!localTerminalId) return;

    try {
      // 调用后端API关闭本地shell进程
      await invoke('close_local_terminal', {
        terminalId: localTerminalId,
      });
      
      // 清理xterm实例
      if (xtermRef.current) {
        xtermRef.current.dispose();
        xtermRef.current = null;
      }
      
      if (fitAddonRef.current) {
        fitAddonRef.current = null;
      }
      
      setLocalTerminalId(null);
      setLocalTerminalOpen(false);
      
      toast.success('本地终端已关闭');
    } catch (error) {
      console.error('Failed to close local terminal:', error);
      toast.error('关闭本地终端失败');
    }
  }, [localTerminalId]);

  // 监听本地终端输出
  const listenToLocalTerminalOutput = useCallback(() => {
    if (!localTerminalId) return;

    const unlisten = listen('local-terminal-output', (event: any) => {
      const { terminal_id, data } = event.payload;
      if (terminal_id === localTerminalId && xtermRef.current) {
        xtermRef.current.write(data);
      }
    });

    return unlisten;
  }, [localTerminalId]);

  useEffect(() => {
    const unlistenOutput = listenToLocalTerminalOutput();

    return () => {
      if (unlistenOutput) {
        unlistenOutput.then(fn => fn());
      }
    };
  }, [listenToLocalTerminalOutput]);

  // 处理窗口大小变化
  useEffect(() => {
    const handleResize = () => {
      if (fitAddonRef.current && localTerminalOpen) {
        setTimeout(() => {
          fitAddonRef.current?.fit();
        }, 100);
      }
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, [localTerminalOpen]);

  // 组件卸载时清理
  useEffect(() => {
    return () => {
      closeLocalTerminal();
    };
  }, []);

  const renderNavigationItem = (item: NavigationItem) => {
    const isActive = location.pathname.startsWith(item.path);
    let badge = 0;

    // 根据路径显示相应的活动数量
    switch (item.path) {
      case '/connections':
        badge = activeConnectionsCount;
        break;
      case '/terminal':
        badge = activeTerminalsCount;
        break;
      case '/tunnels':
        badge = activeTunnelsCount;
        break;
      default:
        badge = 0;
    }

    return (
      <ListItem key={item.path} disablePadding>
        <Tooltip title={item.description} placement="right">
          <ListItemButton
            selected={isActive}
            onClick={() => handleNavigate(item.path)}
            sx={{
              borderRadius: 1,
              mx: 1,
              mb: 0.5,
              '&.Mui-selected': {
                backgroundColor: 'primary.main',
                color: 'primary.contrastText',
                '&:hover': {
                  backgroundColor: 'primary.dark',
                },
                '& .MuiListItemIcon-root': {
                  color: 'primary.contrastText',
                },
              },
            }}
          >
            <ListItemIcon
              sx={{
                minWidth: 40,
                color: isActive ? 'inherit' : 'text.secondary',
              }}
            >
              {badge > 0 ? (
                <Badge badgeContent={badge} color="secondary">
                  {item.icon}
                </Badge>
              ) : (
                item.icon
              )}
            </ListItemIcon>
            <ListItemText
              primary={item.label}
              primaryTypographyProps={{
                fontSize: '0.875rem',
                fontWeight: isActive ? 600 : 400,
              }}
            />
          </ListItemButton>
        </Tooltip>
      </ListItem>
    );
  };

  const drawer = (
    <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* 侧边栏头部 */}
      <Box
        sx={{
          p: 2,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          borderBottom: 1,
          borderColor: 'divider',
        }}
      >
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <TerminalIcon color="primary" />
          <Typography variant="h6" component="div" sx={{ fontWeight: 600 }}>
            RustShell
          </Typography>
        </Box>
        <IconButton
          size="small"
          onClick={toggleSidebar}
          sx={{ display: { sm: 'none' } }}
        >
          <CloseIcon />
        </IconButton>
      </Box>

      {/* 导航菜单 */}
      <Box sx={{ flex: 1, py: 1 }}>
        <List>
          {navigationItems.map(renderNavigationItem)}
        </List>
      </Box>

      {/* 侧边栏底部信息 */}
      <Box sx={{ p: 2, borderTop: 1, borderColor: 'divider' }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
          <InfoIcon fontSize="small" color="action" />
          <Typography variant="caption" color="text.secondary">
            状态信息
          </Typography>
        </Box>
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
          <Typography variant="caption" color="text.secondary">
            活动连接: {activeConnectionsCount}
          </Typography>
          <Typography variant="caption" color="text.secondary">
            活动终端: {activeTerminalsCount}
          </Typography>
          <Typography variant="caption" color="text.secondary">
            活动隧道: {activeTunnelsCount}
          </Typography>
        </Box>
      </Box>
    </Box>
  );

  return (
    <Box sx={{ display: 'flex', height: '100vh' }}>
      {/* 顶部应用栏 */}
      <AppBar
        position="fixed"
        sx={{
          width: { sm: sidebarOpen ? `calc(100% - ${DRAWER_WIDTH}px)` : '100%' },
          ml: { sm: sidebarOpen ? `${DRAWER_WIDTH}px` : 0 },
          transition: 'width 0.3s, margin 0.3s',
          zIndex: (theme) => theme.zIndex.drawer + 1,
        }}
      >
        <Toolbar>
          <IconButton
            color="inherit"
            aria-label="toggle sidebar"
            edge="start"
            onClick={toggleSidebar}
            sx={{ mr: 2 }}
          >
            <MenuIcon />
          </IconButton>
          
          <Typography variant="h6" noWrap component="div" sx={{ flexGrow: 1 }}>
            {navigationItems.find(item => location.pathname.startsWith(item.path))?.label || 'RustShell'}
          </Typography>

          {/* 本地终端切换按钮 */}
          <Tooltip title={localTerminalOpen ? '隐藏本地终端' : '显示本地终端'}>
            <IconButton color="inherit" onClick={toggleLocalTerminal}>
              <Badge badgeContent={localTerminalId ? 1 : 0} color="success">
                <TerminalIcon />
              </Badge>
            </IconButton>
          </Tooltip>

          {/* 通知图标 */}
          <IconButton color="inherit">
            <Badge badgeContent={unreadNotifications} color="secondary">
              <NotificationsIcon />
            </Badge>
          </IconButton>
        </Toolbar>
      </AppBar>

      {/* 侧边栏 */}
      <Box
        component="nav"
        sx={{ width: { sm: sidebarOpen ? DRAWER_WIDTH : 0 }, flexShrink: { sm: 0 } }}
      >
        <Drawer
          variant="temporary"
          open={sidebarOpen}
          onClose={toggleSidebar}
          ModalProps={{
            keepMounted: true, // 更好的移动端性能
          }}
          sx={{
            display: { xs: 'block', sm: 'none' },
            '& .MuiDrawer-paper': {
              boxSizing: 'border-box',
              width: DRAWER_WIDTH,
            },
          }}
        >
          {drawer}
        </Drawer>
        <Drawer
          variant="persistent"
          open={sidebarOpen}
          sx={{
            display: { xs: 'none', sm: 'block' },
            '& .MuiDrawer-paper': {
              boxSizing: 'border-box',
              width: DRAWER_WIDTH,
              position: 'relative',
              height: '100vh',
            },
          }}
        >
          {drawer}
        </Drawer>
      </Box>

      {/* 主内容区域 */}
      <Box
        component="main"
        sx={{
          flexGrow: 1,
          width: { sm: sidebarOpen ? `calc(100% - ${DRAWER_WIDTH}px)` : '100%' },
          transition: 'width 0.3s',
          display: 'flex',
          flexDirection: 'column',
          height: '100vh',
        }}
      >
        {/* 为顶部应用栏留出空间 */}
        <Toolbar />
        
        {/* 本地终端区域 */}
        <Collapse in={localTerminalOpen}>
          <Box
            sx={{
              height: localTerminalHeight,
              backgroundColor: '#1a1a1a',
              borderBottom: '1px solid #333',
              position: 'relative',
              display: 'flex',
              flexDirection: 'column',
            }}
          >
            {/* 终端标题栏 */}
            <Box
              sx={{
                height: 32,
                backgroundColor: '#2d2d2d',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                px: 2,
                borderBottom: '1px solid #333',
              }}
            >
              <Typography
                variant="caption"
                sx={{ color: '#fff', fontFamily: 'monospace' }}
              >
                本地终端 {localTerminalId && `(${localTerminalId.slice(0, 8)})`}
              </Typography>
              <Box>
                <IconButton
                  size="small"
                  onClick={closeLocalTerminal}
                  sx={{ color: '#fff', p: 0.5 }}
                >
                  <CloseIcon fontSize="small" />
                </IconButton>
              </Box>
            </Box>

            {/* 终端内容区域 */}
            <Box
              ref={terminalRef}
              sx={{
                flex: 1,
                '& .xterm': {
                  height: '100% !important',
                },
                '& .xterm-viewport': {
                  backgroundColor: '#1a1a1a !important',
                },
              }}
            />

            {/* 调整大小的拖拽条 */}
            <Box
              sx={{
                height: 4,
                backgroundColor: '#333',
                cursor: 'ns-resize',
                '&:hover': {
                  backgroundColor: '#555',
                },
              }}
              onMouseDown={(e) => {
                const startY = e.clientY;
                const startHeight = localTerminalHeight;

                const handleMouseMove = (e: MouseEvent) => {
                  const deltaY = e.clientY - startY;
                  const newHeight = Math.max(200, Math.min(600, startHeight + deltaY));
                  setLocalTerminalHeight(newHeight);
                };

                const handleMouseUp = () => {
                  document.removeEventListener('mousemove', handleMouseMove);
                  document.removeEventListener('mouseup', handleMouseUp);
                  // 调整终端大小
                  setTimeout(() => {
                    fitAddonRef.current?.fit();
                  }, 100);
                };

                document.addEventListener('mousemove', handleMouseMove);
                document.addEventListener('mouseup', handleMouseUp);
              }}
            />
          </Box>
        </Collapse>
        
        {/* 页面内容 */}
        <Box sx={{ flex: 1, overflow: 'hidden' }}>
          <Outlet />
        </Box>
      </Box>
    </Box>
  );
};

export default Layout;